package org.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.entity.User;
import org.example.service.IRoleService;
import org.example.service.IUserService;
import org.example.util.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author guocb
 * @since 2021-03-01
 */
@Controller
@RequestMapping("/user")
public class UserController {


    @Autowired
    IUserService userService;

    @Autowired
    IRoleService roleService;

    @Autowired
    PasswordEncoder passwordEncoder;

    ///user/list  = hasAuthority("/user/list")
    //对请求权限控制  是否有改权限
    //在请求之前
    @PreAuthorize("hasAuthority('user_list')")
//    @RolesAllowed(value = {"SMBMS_ADMIN","SMBMS_HR"}) //允许访问的角色
//    @PostAuthorize() //请求之后 在返回视图之前
    @GetMapping("list")
    public String list(@RequestParam(defaultValue = "1", required = false) Long pageIndex,
                       String queryname,
                       Long queryUserRole,
                       Model model) {
        //查询条件封装
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (queryname != null && queryname != "")
            queryWrapper.like(User.USERNAME, queryname);
        if (queryUserRole != null && queryUserRole != 0)
            queryWrapper.eq(User.USERROLE, queryUserRole);
        //分页
        PageInfo<User> pageInfo = new PageInfo<User>(pageIndex, 10);
        pageInfo = (PageInfo<User>) userService.selectUserPage(pageInfo, queryWrapper);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("queryname",queryname);
        model.addAttribute("queryUserRole",queryUserRole);
        model.addAttribute("roleList", roleService.list());
        return "userlist";
    }

    //跳转到添加用户页面
    @PreAuthorize("hasAuthority('user_toadd')")
    @GetMapping("toadd")
    public String toAdd(Model model) {
        //所有的角色
        model.addAttribute("roleList", roleService.list());
        return "useradd";
    }

    @PreAuthorize("hasAuthority('user_add')")
    @PostMapping("add")
    public String add(User user,
                      MultipartFile idPicPathFile,
                      Model model) {
        if(idPicPathFile.isEmpty()){
            model.addAttribute("msg", "请选择证件照");
            return "useradd";
        }
        try {
            String ext = idPicPathFile.getOriginalFilename().substring(idPicPathFile.getOriginalFilename().lastIndexOf("."));
            String fileName = System.currentTimeMillis() + ext;
            idPicPathFile.transferTo(new File("E:\\files\\"+fileName));
            user.setIdPicPath(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //当前登录用户
        org.springframework.security.core.userdetails.User detailUser =
                (org.springframework.security.core.userdetails.User)
                        SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User loginUser = userService.getOne(new QueryWrapper<User>().eq(User.USERCODE,
                    detailUser.getUsername()));
        user.setCreatedBy(loginUser.getId());

        //加密的密码
        String password = new BCryptPasswordEncoder().encode(user.getUserPassword());
        user.setUserPassword(password);
        boolean flag = userService.save(user);
        if (flag) {
            return "redirect:list";
        }
        model.addAttribute("msg", "添加失败");
        return "useradd";
    }

    @PreAuthorize("hasAuthority('user_get')")
    @GetMapping("get")
    public String get(Long id, Model model) {
        User user = userService.getById(id);
        model.addAttribute("user", user);
        model.addAttribute("roleList", roleService.list());
        return "usermodify";
    }

    @PreAuthorize("hasAuthority('user_update')")
    @PostMapping("update")
    public String update(User user, Model model) {
        //根据id更新对象属性
        boolean flag = userService.updateById(user);
        if (flag) {
            return "redirect:list";
        }
        return "redirect:get?id=" + user.getId(); //重定向到查询
    }

    @PreAuthorize("hasAuthority('user_delete')")
    @ResponseBody
    @GetMapping("delete")
    public Boolean delete(Long id) {
        return userService.removeById(id);
    }
}
